import React, { Component } from 'react'

import "./shopp_detail.less"

import { connect } from "react-redux"
import action from '../../../store/action/index.js'
import { withRouter } from 'react-router-dom'

import cookies from 'js-cookie'
class Shoppetail extends Component {

    state = {
        type: [],//所选规格
        num: 1,//设定数量
        allmoney: 0,//总价
        price: 0,//商品单价
        timer: compareTimer(),
    }

    render() {
        let { listitmedetail, addCarData, cardata, closeTypeBox, choosetype, getChooseType, openLoginHint } = this.props
        let { num, type, price, timer } = this.state
        return (
            <div className="shopp_detail_box animate__animated  animate__slideInUp" ref={(box) => this.shopp_detail_box = box}>
                {/* 顶部内容信息 */}
                <div className="shopp_detail_top_box">
                    <div className="shopp_detail_top_img">
                        <img src={listitmedetail.commodity_images[0]} />
                    </div>
                    <div className="shopp_detail_top_cont">
                        <h1>{listitmedetail.commodity_namer}</h1>
                        <p><i>￥{price}元</i></p>
                        <span className="iconfont icon-delete2 shopp_detail_top_cont_del"
                            onClick={(e) => {
                                if (type.length === 0) {
                                    type = choosetype.type
                                    closeTypeBox(type, num)
                                } else {
                                    closeTypeBox(type, num)
                                }
                            }}
                        ></span>
                    </div>
                </div>
                {/* 底部内容 */}
                <div className="shopp_detail_type_box">
                    {/* 商品类型 */}
                    <div className="item_detail_cont_type">
                        {
                            listitmedetail.types.length > 0 ?
                                listitmedetail.types.map((item, itemindex) => {
                                    return <div className="item_detail_cont_type_title" key={itemindex}>
                                        <h2>{item.shop_typeMess}</h2>
                                        <div className="item_detail_cont_type_cont">
                                            {
                                                item.shop_type.map((typelistitem, typelistindex) => {
                                                    return <span onClick={(e) => { this.typeGenre(itemindex, typelistindex, e) }} key={typelistindex}>{typelistitem}</span>
                                                })
                                            }
                                        </div>
                                    </div>
                                })
                                : null
                        }
                    </div>

                    {/* 数量加减 */}
                    <div className="item_detail_cont_type_btn">
                        <p className="item_detail_cont_type_btn_p">
                            <span className="item_detail_cont_type_del" onClick={(e) => {
                                this.addNum(e)
                            }}>-</span>
                            <span>{num}</span>
                            <span className="item_detail_cont_type_add" onClick={(e) => {
                                this.delNum(e)
                            }}>+</span>
                        </p>
                    </div>

                    {/* 加入购物车按钮 */}
                    <div className="item_detail_btm_box">
                        {/* 添加到购物车 */}
                        <div>
                            {
                                this.state.price !== 0 && timer ?
                                    <button className="item_detail_btm_btn" ref="item_detail_btm_btn" onClick={(e) => {
                                        // console.log(cookies.get('user_id'));
                                        if (cookies.get('user_id') !== undefined) {
                                            if (type.length > 0) {
                                                console.log(this.state.price);
                                                addCarData({//调取接口存入到后台
                                                    commodity_id: listitmedetail.commodity_id,
                                                    number: num,
                                                    all_price: ((this.state.price * 1000) * num) / 1000,
                                                    user_id: cookies.get('user_id'),
                                                    mess: type.join("/"),
                                                    prices: this.state.price
                                                })
                                                // 关闭页面时清理当前页数据
                                                closeTypeBox(type, num)

                                                getChooseType({})
                                                this.setState({ type: [], num: 1 })
                                                // 跳路由
                                                sessionStorage.setItem("flag", JSON.stringify(true))
                                                this.props.history.push('/list')
                                            } else {
                                                // 在用户没有点击选规格时使用默认规格
                                                if (choosetype.type) {
                                                    console.log(this.state.price);
                                                    addCarData({//调取接口存入到后台
                                                        commodity_id: listitmedetail.commodity_id,
                                                        number: num,
                                                        all_price: ((this.state.price * 1000) * num) / 1000,
                                                        user_id: cookies.get('user_id'),
                                                        mess: type.join("/"),
                                                        prices: this.state.price
                                                    })

                                                    // 关闭页面时清理当前页数据
                                                    closeTypeBox(type, num)

                                                    getChooseType({})
                                                    this.setState({ type: [], num: 1 })
                                                    // 跳路由
                                                    sessionStorage.setItem("flag", JSON.stringify(true))
                                                    this.props.history.push('/list')
                                                } else {
                                                    console.log('没有选规格')
                                                }
                                            }
                                        } else {
                                            openLoginHint()
                                        }


                                    }}>加入购物车</button>
                                    : (
                                        timer ? <button className="item_detail_btm_btn2" >加入购物车</button>
                                            : <button className="item_detail_btm_btn2" onClick={() => {
                                                console.log("暂停营业，店内整顿");
                                            }}>加入购物车</button>
                                    )
                            }
                        </div>
                    </div>

                </div>

            </div >
        )
    }

    componentDidMount() {
        let { choosetype, listitmedetail } = this.props
        if (choosetype.commodity_id !== undefined) {
            // 设置 一进入选规格默认 
            listitmedetail.types.forEach((typeitem, typeindex) => {
                typeitem.shop_type.forEach((ttypeitem, ttypeindex) => {
                    // console.log(ttypeitem);
                    if (choosetype.type[0] === ttypeitem) {
                        document.querySelectorAll('.item_detail_cont_type_cont')[typeindex]
                            .querySelectorAll('.item_detail_cont_type_cont span')[ttypeindex]
                            .className = "span_active"

                    } else if (choosetype.type[1] === ttypeitem) {
                        document.querySelectorAll('.item_detail_cont_type_cont')[typeindex]
                            .querySelectorAll('.item_detail_cont_type_cont span')[ttypeindex]
                            .className = "span_active"
                    } else if (choosetype.type[2] === ttypeitem) {
                        document.querySelectorAll('.item_detail_cont_type_cont')[typeindex]
                            .querySelectorAll('.item_detail_cont_type_cont span')[ttypeindex]
                            .className = "span_active"
                    }
                })
            })
            this.setState({ num: choosetype.num })
        }
    }

    // 选规格
    typeGenre = (itemindex, typelistindex, e) => {
        e.stopPropagation()
        document.querySelectorAll('.item_detail_cont_type_cont')[itemindex]
            .querySelectorAll('.item_detail_cont_type_cont span')
            .forEach(item => {
                item.className = ""
            })
        document.querySelectorAll('.item_detail_cont_type_cont')[itemindex]
            .querySelectorAll('.item_detail_cont_type_cont span')[typelistindex]
            .className = "span_active"

        this.getTypes(itemindex, typelistindex, e)
    }

    getTypes = (itemindex, typelistindex, e) => {//所选规格
        e.stopPropagation()
        let arr = []
        // 获取选中高亮
        document.querySelectorAll('.item_detail_cont_type_cont span').forEach(item => {
            if (item.className === "span_active") {
                arr.push(item.innerHTML)
            }
        })

        this.setState({ type: arr })

        // 动态获取价格  通过判断选中尺寸
        arr.forEach(item => {
            if (this.props.listitmedetail.types[itemindex].shop_typeMess === "尺寸/口味") {
                if (item === this.props.listitmedetail.types[itemindex].shop_type[typelistindex]) {
                    this.setState({ price: this.props.listitmedetail.commodity_unitPrice[typelistindex] })
                }
            }

        })
    }

    // 数量的加减
    addNum = (e) => {
        e.stopPropagation()
        let { num } = this.state
        if (num > 1) {
            this.setState({ num: num -= 1 })
        }
    }
    delNum = (e) => {
        e.stopPropagation()
        let { num } = this.state
        this.setState({ num: num += 1 })
    }


}

export default connect(state => state.foodf, action.foodf)(withRouter(Shoppetail))


function compareTimer() {
    let year = new Date().getFullYear()
    let month = new Date().getMonth() + 1
    let date = new Date().getDate()
    let timerNow = new Date().getTime()
    let timer1 = new Date(`${year}/${month}/${date} 0:00`).getTime()
    let timer2 = new Date(`${year}/${month}/${date} 24:00`).getTime()

    if (timerNow > timer1 && timerNow < timer2) {
        return true
    } else {
        return false
    }

}